<template>
  <div class="published-tasks">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>我的发布</span>
          <el-button type="primary" @click="$router.push('/user/new-task')">
            发布新任务
          </el-button>
        </div>
      </template>
      
      <!-- 搜索筛选 -->
      <div class="search-section">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-select v-model="filters.schoolId" placeholder="选择学校" clearable>
              <el-option
                v-for="school in schools"
                :key="school.id"
                :label="school.name"
                :value="school.id"
              />
            </el-select>
          </el-col>
          
          <el-col :span="6">
            <el-select v-model="filters.status" placeholder="任务状态" clearable>
              <el-option label="等待接取" :value="0" />
              <el-option label="已取消" :value="1" />
              <el-option label="进行中" :value="2" />
              <el-option label="已完成" :value="3" />
            </el-select>
          </el-col>
          
          <el-col :span="6">
            <el-input
              v-model="filters.keyword"
              placeholder="搜索关键词"
              @keyup.enter="loadTasks"
            />
          </el-col>
          
          <el-col :span="6">
            <el-button type="primary" @click="loadTasks">搜索</el-button>
            <el-button @click="resetFilters">重置</el-button>
          </el-col>
        </el-row>
      </div>
      
      <!-- 排序 -->
      <div class="sort-section">
        <el-radio-group v-model="sortBy" @change="loadTasks">
          <el-radio-button label="time">时间最新</el-radio-button>
          <el-radio-button label="reward-asc">价格升序</el-radio-button>
          <el-radio-button label="reward-desc">价格降序</el-radio-button>
        </el-radio-group>
      </div>
      
      <!-- 任务列表 -->
      <div class="task-list" v-loading="loading">
        <div v-if="tasks.length === 0" class="empty-state">
          <el-empty description="暂无任务" />
        </div>
        
        <div v-else>
          <div v-for="task in tasks" :key="task.id" class="task-item">
            <el-card class="task-card">
              <div class="task-header">
                <h3 class="task-title">{{ task.title }}</h3>
                <el-tag :type="getStatusType(task.status)">
                  {{ getStatusText(task.status) }}
                </el-tag>
              </div>
              
              <div class="task-content">
                <p class="task-description">{{ task.description }}</p>
                
                <div class="task-meta">
                  <span class="meta-item">
                    <el-icon><Money /></el-icon>
                    奖励：¥{{ task.reward }}
                  </span>
                  <span class="meta-item">
                    <el-icon><Clock /></el-icon>
                    发布时间：{{ formatTime(task.createTime) }}
                  </span>
                  <span v-if="task.endTime" class="meta-item">
                    <el-icon><Calendar /></el-icon>
                    结束时间：{{ task.endTime }}
                  </span>
                  <span v-if="task.status === 2 && task.accepterName" class="meta-item accepter-info">
                    <el-icon><User /></el-icon>
                    接取者：{{ task.accepterName }} ({{ task.accepterStudentId }})
                  </span>
                  <span v-if="task.status === 3 && task.accepterName" class="meta-item completer-info">
                    <el-icon><Check /></el-icon>
                    完成者：{{ task.accepterName }} ({{ task.accepterStudentId }})
                  </span>
                  <span v-if="task.status === 0" class="meta-item waiting-info">
                    <el-icon><Clock /></el-icon>
                    等待接取中...
                  </span>
                  <span v-if="task.status === 1" class="meta-item cancelled-info">
                    <el-icon><Close /></el-icon>
                    任务已取消
                  </span>
                </div>
              </div>
              
            <div class="task-actions">
              <el-button
                v-if="task.status === 0"
                size="small"
                type="danger"
                @click="cancelTask(task)"
              >
                取消任务
              </el-button>
              <el-button
                v-if="task.status === 2"
                size="small"
                type="success"
                @click="completeTask(task)"
              >
                确认完成
              </el-button>
              <el-button
                v-if="task.status === 1"
                size="small"
                disabled
              >
                已取消
              </el-button>
              <el-button
                v-if="task.status === 3"
                size="small"
                type="info"
                disabled
              >
                已完成
              </el-button>
            </div>
            </el-card>
          </div>
        </div>
      </div>
      
      <!-- 分页 -->
      <div class="pagination" v-if="tasks.length > 0">
      <el-pagination
        :current-page="currentPage"
        :page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="loadTasks"
        @current-change="loadTasks"
      />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '../../stores/user'
import api from '../../utils/api'

const userStore = useUserStore()
const loading = ref(false)
const tasks = ref([])
const schools = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const sortBy = ref('time')

const filters = reactive({
  schoolId: '',
  status: '',
  keyword: ''
})

const getStatusText = (status) => {
  const statusMap = {
    0: '等待接取',
    1: '已取消',
    2: '进行中',
    3: '已完成'
  }
  return statusMap[status] || '未知'
}

const getStatusType = (status) => {
  const typeMap = {
    0: 'warning',
    1: 'info',
    2: 'primary',
    3: 'success'
  }
  return typeMap[status] || 'info'
}

const formatTime = (time) => {
  if (!time) return ''
  return new Date(time).toLocaleString()
}

// 移除不需要的函数，因为这是用户自己的发布页面

const loadTasks = async () => {
  loading.value = true
  try {
    // 获取当前用户发布的任务
    const response = await api.get('/user/tasks/published')
    if (response.data.code === 200) {
      let filteredTasks = response.data.data
      
      // 应用筛选条件
      if (filters.status !== '') {
        filteredTasks = filteredTasks.filter(task => task.status === filters.status)
      }
      
      if (filters.keyword) {
        const keyword = filters.keyword.toLowerCase()
        filteredTasks = filteredTasks.filter(task => 
          task.title.toLowerCase().includes(keyword) || 
          task.description.toLowerCase().includes(keyword)
        )
      }
      
      // 应用排序
      if (sortBy.value === 'time') {
        filteredTasks.sort((a, b) => new Date(b.createTime) - new Date(a.createTime))
      } else if (sortBy.value === 'reward-asc') {
        filteredTasks.sort((a, b) => a.reward - b.reward)
      } else if (sortBy.value === 'reward-desc') {
        filteredTasks.sort((a, b) => b.reward - a.reward)
      }
      
      tasks.value = filteredTasks
      total.value = filteredTasks.length
    }
  } catch (error) {
    console.error('加载已发布任务失败:', error)
    ElMessage.error('加载任务失败')
  } finally {
    loading.value = false
  }
}

const loadSchools = async () => {
  try {
    const response = await api.get('/auth/schools')
    if (response.data.code === 200) {
      schools.value = response.data.data
    }
  } catch (error) {
    console.error('加载学校列表失败:', error)
  }
}

const resetFilters = () => {
  filters.schoolId = ''
  filters.status = ''
  filters.keyword = ''
  loadTasks()
}


const cancelTask = async (task) => {
  try {
    await ElMessageBox.confirm('确定要取消这个任务吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await api.post(`/user/tasks/${task.id}/cancel`)
    if (response.data.code === 200) {
      ElMessage.success('取消成功')
      loadTasks()
    } else {
      ElMessage.error(response.data.message)
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('取消失败')
    }
  }
}

// 移除acceptTask函数，因为这是用户自己的发布页面

const completeTask = async (task) => {
  try {
    await ElMessageBox.confirm('确定要完成这个任务吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await api.post(`/user/tasks/${task.id}/complete`)
    if (response.data.code === 200) {
      ElMessage.success('完成成功')
      loadTasks()
    } else {
      ElMessage.error(response.data.message)
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('完成失败')
    }
  }
}

onMounted(() => {
  loadTasks()
  loadSchools()
})
</script>

<style scoped>
.published-tasks {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-section {
  margin-bottom: 20px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 4px;
}

.sort-section {
  margin-bottom: 20px;
}

.task-list {
  min-height: 400px;
}

.empty-state {
  text-align: center;
  padding: 40px;
}

.task-item {
  margin-bottom: 20px;
}

.task-card {
  transition: box-shadow 0.3s;
}

.task-card:hover {
  box-shadow: 0 4px 12px rgba(0,0,0,0.1);
}

.task-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.task-title {
  margin: 0;
  color: #333;
  font-size: 18px;
}

.task-content {
  margin-bottom: 15px;
}

.task-description {
  color: #666;
  line-height: 1.6;
  margin-bottom: 15px;
}

.task-meta {
  display: flex;
  gap: 20px;
  flex-wrap: wrap;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 5px;
  color: #666;
  font-size: 14px;
}

.accepter-info {
  color: #409eff !important;
  font-weight: 500;
}

.completer-info {
  color: #67c23a !important;
  font-weight: 500;
}

.waiting-info {
  color: #e6a23c !important;
  font-weight: 500;
}

.cancelled-info {
  color: #f56c6c !important;
  font-weight: 500;
}

.task-actions {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.pagination {
  margin-top: 20px;
  text-align: center;
}
</style>

